package _dp_base;

import java.util.Arrays;
import java.util.List;

/**
 * 120. 三角形最小路径和
 */
public class No120 {
    private List<List<Integer>> triangle;
    private int[][] cache;

    /**
     * 1. 递归
     */
    public int minimumTotal1(List<List<Integer>> triangle) {
        this.triangle = triangle;
        int n = triangle.size();
        cache = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = Integer.MAX_VALUE;
            }
        }
        int answer = Integer.MAX_VALUE;
        for (int j = 0; j < n; j++) {
            answer = Math.min(dfs(n - 1, j), answer);
        }
        return answer;
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return Integer.MAX_VALUE / 2;
        else if (cache[i][j] != Integer.MAX_VALUE) return cache[i][j];
        else if (i == 0 && j == 0) return cache[i][j] = triangle.get(i).get(j);
        else if (j == 0) return cache[i][j] = dfs(i - 1, j) + triangle.get(i).get(j);
        else if (j == triangle.get(i).size() - 1) return cache[i][j] = dfs(i - 1, j - 1) + triangle.get(i).get(j);
        else return cache[i][j] = Math.min(dfs(i - 1, j - 1), dfs(i - 1, j)) + triangle.get(i).get(j);
    }

    /**
     * 2. 迭代
     */
    public int minimumTotal2(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[][] f = new int[n + 1][n + 1];
        Arrays.fill(f[0], Integer.MAX_VALUE);

        for (int i = 0; i < n; i++) {
            f[i + 1][0] = Integer.MAX_VALUE;
            for (int j = 0; j < triangle.get(i).size(); j++) {
                if (i == 0 && j == 0) f[i + 1][j + 1] = triangle.get(i).get(j);
                else if (j == 0) f[i + 1][j + 1] = f[i][j + 1] + triangle.get(i).get(j);
                else if (j == triangle.get(i).size() - 1) f[i + 1][j + 1] = f[i][j] + triangle.get(i).get(j);
                else f[i + 1][j + 1] = Math.min(f[i][j], f[i][j + 1]) + triangle.get(i).get(j);
            }
        }


        int answer = Integer.MAX_VALUE;
        for (int j = 0; j < n; j++) {
            answer = Math.min(f[n][j + 1], answer);
        }
        return answer;
    }

    /**
     * 4. 一维数组
     */
    public int minimumTotal4(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[] f = new int[n];
        Arrays.fill(f, Integer.MAX_VALUE);
        f[0] = triangle.get(0).get(0);

        for (int i = 1; i < n; i++) {
            int pre = f[0];
            for (int j = 0; j < triangle.get(i).size(); j++) {
                int temp = f[j];
                if (j == 0) f[j] = f[j] + triangle.get(i).get(j);
                else if (j == triangle.get(i).size() - 1) f[j] = pre + triangle.get(i).get(j);
                else f[j] = Math.min(pre, f[j]) + triangle.get(i).get(j);
                pre = temp;
            }
        }

        return Arrays.stream(f).min().orElse(Integer.MAX_VALUE);
    }
}
